<?php

namespace Bxy\Jwt\method;



use Bxy\Jwt\exception\JwtException;
use Bxy\Jwt\exception\TokenExpiredException;
use Bxy\Jwt\Jwt;
use Bxy\Jwt\TokenInterface;
use Hyperf\Di\Annotation\Inject;

/**
 * Class JwtHeader
 * @package Bxy\Jwt\method
 * User:boss.zhang
 * 待完善
 */
class JwtHeader implements  \Bxy\Jwt\AuthInterface
{
    protected $headerName = 'Authorization';
    protected $pattern;
    /**
     * @Inject()
     * @var TokenInterface
     */
    protected $jwt;
    public function authenticate(\Psr\Http\Message\ServerRequestInterface $request,$isPublic,$isWhitelist,$isCheck)
    {
        // TODO: Implement authenticate() method.
        $authToken = $this->getToken($request);

        if($authToken!==null){
            $flag =  $this->checkToken($authToken);
            if($isCheck==true || $isWhitelist==true){
	            if($flag==null){
		            throw new  JwtException('token有误',4001);
	            }elseif ($flag === 'time_out'){
		            throw new TokenExpiredException('token已经过期',4002);
	            }else{
		            return true;
	            }
            }
            return true;
        }
        if($isCheck==true){
	        throw new  JwtException('请传入token',4001);
        }
    }

    public function challenge(\Hyperf\HttpServer\Contract\ResponseInterface $response): \Hyperf\HttpServer\Contract\ResponseInterface
    {
        // TODO: Implement challenge() method.
        return  $response;
    }
    public function setPattern(string $pattern): void
    {
        $this->pattern = $pattern;
    }
    protected function getToken(\Psr\Http\Message\ServerRequestInterface $request): ?string
    {
        $authHeaders = $request->getHeader($this->headerName);
        $authHeader = \reset($authHeaders);
        if($this->headerName){
           $this->setPattern("/Bearer\s(\S+)/");
        }
        if ($authHeader !== false) {
            if ($this->pattern !== null) {
                if (preg_match($this->pattern, $authHeader, $matches)) {
                    $authHeader = $matches[1];
                } else {
                    return null;
                }
            }
            return $authHeader;
        }
        return null;
    }

    public function checkToken($token)
    {
       return  $this->jwt->verify($token);
    }
}